package com.example.emb.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.emb.entity.*;
import com.example.emb.mapper.*;
import com.example.emb.service.TeacherImpStuService;
import com.example.emb.service.exception.DeleteErrorException;
import com.example.emb.service.exception.UsrNotFoundException;
import com.example.emb.service.exception.repeatClassException;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class TeacherImpStuServiceImpl implements TeacherImpStuService {
    @Autowired
    ClasstableMapper classtableMapper;
    @Autowired
    UsrtableMapper usrtableMapper;
    @Autowired
    ClassdtableMapper classdtableMapper;
    @Autowired
    YeartableMapper yeartableMapper;
    @Autowired
    ClassdStutableMapper classdStutableMapper;
    @Autowired
    GroupdtableMapper groupdtableMapper;
    @Autowired
    GrouptableMapper grouptableMapper;


    @Override
    public void newClass(String Name, Date modifiedTime, Date endTime, int year) {
        QueryWrapper<Classtable> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("year",year)
                .eq("className",Name);
        Classtable classtable=classtableMapper.selectOne(queryWrapper);
        Classtable class1=new Classtable();
        java.sql.Date sqlDateM = new java.sql.Date(modifiedTime.getTime());
        java.sql.Date sqlDateE = new java.sql.Date(endTime.getTime());
        class1.setClassName(Name)
                .setModifiedTime(sqlDateM)
                .setEndTime(sqlDateE)
                .setYear(year);
        if(classtable!=null){
            throw new repeatClassException("重复建立相同班级");
        }
        else
            classtableMapper.insert(class1);
    }

    @Override
    public void ImportStuByExcel(MultipartFile file ,int classType,int classId) {
        try(Workbook workbook = WorkbookFactory.create(file.getInputStream())){
            System.out.println("begin");
            Sheet sheet = workbook.getSheetAt(0);
            int TeacherClassId=0;
            int StaticClassId=0;
            for (int rowIndex = 1; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
                System.out.println(rowIndex+"-"+sheet.getLastRowNum());
                Row row = sheet.getRow(rowIndex);
                //出现空行的问题
                if(row==null)
                    continue;
                Cell cell = row.getCell(0);
                if(cell==null){
                    break;
                }
                String studentId = row.getCell(0).getStringCellValue();
                if(studentId==""){
                    break;
                }
                System.out.println(studentId);
                String Stuname = row.getCell(1).getStringCellValue();
                System.out.println(Stuname);
                String college=row.getCell(2).getStringCellValue();
                System.out.println(college);
                String className=row.getCell(3).getStringCellValue();
                System.out.println(className);
                String TeachingClassName=row.getCell(4).getStringCellValue();
                System.out.println(TeachingClassName);
                int year=0;
                Cell cell1 = row.getCell(5);
                switch (cell1.getCellTypeEnum()) {
                    case STRING:
                        String value = cell.getStringCellValue();
                        year=Integer.parseInt(value);
                        break;
                    case NUMERIC:
                        // 根据具体需求选择处理方式，比如直接读取为数字，或者将数字转换为字符串
                        Double value1 = cell.getNumericCellValue();
                        year=value1.intValue();
                        break;
                    // 其他类型的处理方式
                    default:
                        // 其他类型的处理方式，比如日期、布尔值等
                        break;
                }
//                Double year1=row.getCell(5).getNumericCellValue();
//                int year=year1.intValue();
//                String year1=row.getCell(5).getStringCellValue();
//                int year=Integer.parseInt(year1);
                System.out.println(year);
                //需要根据行政班级来判断是不是要更具行政班级的创建
                /**
                 * 重写导入逻辑，如果没有行政班级，那就先创建行政班级，然后导入学生资料 成功
                 */
                QueryWrapper yearQueryWrapper=new QueryWrapper();
                yearQueryWrapper.eq("years",year);
                Yeartable yeartable=yeartableMapper.selectOne(yearQueryWrapper);
                if(yeartable==null){
                    Yeartable yeartable1=new Yeartable();
                    yeartable1.setYears(year);
                    yeartableMapper.insert(yeartable1);
                }

                //查询是不是有相应的行政班级了 成功
                QueryWrapper<Classtable> classQueryWrapper=new QueryWrapper<>();
                classQueryWrapper.eq("className",className);
                Classtable classtable=classtableMapper.selectOne(classQueryWrapper);
                if(classtable==null){
                    Classtable classtable1=new Classtable();
                    classtable1.setYear(year)
                            .setClassName(className)
                            .setClassType(2);
                    StaticClassId=classtableMapper.insert(classtable1);
                }
                else
                    StaticClassId=classtable.getClassId();

                //查看教学班级是不是有创建了，没有创建的话新创建一个
//                if(rowIndex==1){
//                    QueryWrapper<Classdtable> queryWrapper=new QueryWrapper<>();
//                    queryWrapper.eq("className",className)
//                            .eq("TeachingClassName",TeachingClassName);
//                    Classdtable classdtable=classdtableMapper.selectOne(queryWrapper);
//                    if(classdtable==null){
//                        Classdtable classdtable1=new Classdtable();
//                        classdtable1.setClassId(classId)
//                                .setClassName(className)
//                                .setTeachingClassName(TeachingClassName);
//                        TeacherClassId=classdtableMapper.insert(classdtable1);
//                    }
//                }

                //先看看学生info中有没有录入，如果没有，先导入到学生表里面
                System.out.println(studentId);
                Usrtable usr=usrtableMapper.selectById(Long.parseLong(studentId));
                Date date=new Date();
                java.sql.Date sqlD=new java.sql.Date(date.getTime());
                if(usr==null){
                    Usrtable newUsr=new Usrtable();
                    newUsr.setPassword(studentId)
                            .setId(Long.parseLong(studentId))
                            .setName(Stuname)
                            .setCollege(college)
                            .setModifiedtime(sqlD)
                            .setClassName(className);
                    usrtableMapper.insert(newUsr);
                }

                //在教学班级表中插入学生
                Classdstutable classdStutable=new Classdstutable();
                classdStutable.setStuId(Long.parseLong(studentId))
                        .setClassId(classId)
                        .setStuName(Stuname)
                        .setClassName(className)
                        .setTeachingClassId(StaticClassId)
                        .setTeachingClassName(TeachingClassName);
                classdStutableMapper.insert(classdStutable);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    public void InsertStu(String uid,int classId,String TeachingClassName) {
        Usrtable usr=usrtableMapper.selectById(Long.parseLong(uid));
        if(usr!=null){
            throw new UsrNotFoundException("该学生已经存在");
        }

        //不存在行政班级就创建一个
        QueryWrapper<Classtable>queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("classType",2)
                .eq("className",TeachingClassName);
        Classtable classtableT=classtableMapper.selectOne(queryWrapper);
        int TeachingClassId=0;
        if(classtableT==null){
            Classtable classtable=new Classtable();
            classtable.setClassType(2)
                    .setClassName(TeachingClassName);
            TeachingClassId=classtableMapper.insert(classtable);
        }

        // 插入到classTable中去
        Classtable classtable=classtableMapper.selectById(classId);
        Classdtable classdtable=classdtableMapper.selectById(TeachingClassId);
        Classdstutable classdStutable=new Classdstutable();
        classdStutable.setClassId(classId)
                .setStuId(Long.parseLong(uid))
                .setTeachingClassId(TeachingClassId)
                .setTeachingClassName(TeachingClassName)
                .setClassName(classtable.getClassName());
        classdStutableMapper.insert(classdStutable);

        //关于小组的逻辑
        // 如果存在group 就直接插入，如果不存在就创建一个再加入
    }

    @Override
    public void DeleteStu(int classStuId) {
        //需要删除两个，教学学生表的还有小组表里面的
        Classdstutable classdStutable=classdStutableMapper.selectById(classStuId);
        if(classdStutableMapper.deleteById(classStuId)==0)
            throw  new DeleteErrorException("班级成员移除失败");
        //删除小组中的成员的内容
        QueryWrapper<Groupdtable> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("Uid",classdStutable.getStuId())
                .eq("GroupId",classdStutable.getGroupId());
        if(groupdtableMapper.delete(queryWrapper)==0){
            throw  new DeleteErrorException("小组成员移除失败");
        }
        Grouptable grouptable=grouptableMapper.selectById(classdStutable.getGroupId());
        grouptable.setGroupNum(grouptable.getGroupNum()-1);
        if(grouptable.getGroupNum()!=0){
            grouptableMapper.updateById(grouptable);
        }
        else
            grouptableMapper.deleteById(grouptable);
        return;
    }

    @Override
    public List<Classdstutable> searchStu(Classdstutable Stu, int TeachingClassId, int classId) {
        QueryWrapper<Classdtable> queryWrapper=new QueryWrapper<>();
        Classdtable classdtable=classdtableMapper.selectById(TeachingClassId);
        Classtable classtable=classtableMapper.selectById(classId);
        QueryWrapper<Classdstutable> queryWrapperStu=new QueryWrapper();
        queryWrapperStu.eq("classId",classId)
                        .eq("className",classtable.getClassName())
                                .eq("stuId",Stu.getStuId())
                                        .eq("stuName",Stu.getStuName())
                                                .eq("groupId",Stu.getGroupId())
                                                        .eq("groupName",Stu.getGroupName());
        List<Usrtable> list=new ArrayList<>();
        List<Classdstutable> list1=classdStutableMapper.selectList(queryWrapperStu);
//        for(Classdstutable classStutableX:list1){
//            list.add(usrtableMapper.selectById(classStutableX.getStuId()));
//        }
        return list1;
    }

}
